from datetime import datetime, timezone
from app.extensions import db
from enum import Enum  # 用于处理 ENUM 类型
class BudgetType(Enum):
    """预算类型：月度/年度"""
    MONTH = 'month'
    YEAR = 'year'
# 6. 预算表（budgets）
class Budget(db.Model):
    __tablename__ = 'budgets'  # 注意表名是复数形式

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='预算唯一标识')
    user_id = db.Column(db.BigInteger, db.ForeignKey('user.user_id'), nullable=False, comment='关联用户 ID')
    type = db.Column(db.Enum(BudgetType), nullable=False, comment='预算类型（月/年度）')  # 关联枚举类型
    year = db.Column(db.Integer, nullable=False, comment='年份')
    month = db.Column(db.Integer, nullable=True, comment='月份（年度预算为 NULL）')
    total_budget = db.Column(db.Numeric(10, 2), nullable=False, comment='总预算金额')
    created_at = db.Column(db.DateTime, nullable=False, comment='创建时间')
    updated_at = db.Column(db.DateTime, nullable=False, comment='更新时间')

    # 唯一约束：同一用户同一时间维度预算唯一（对应 SQL 中的 UNIQUE KEY）
    __table_args__ = (
        db.UniqueConstraint('user_id', 'type', 'year', 'month', name='unique_user_type_year_month'),
    )

    def __repr__(self):
        return f'<Budget {self.id} (user_id: {self.user_id}, type: {self.type.value})>'


class CategoryBudget(db.Model):
    __tablename__ = 'category_budgets'

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='分类预算唯一标识')
    user_id = db.Column(db.BigInteger, db.ForeignKey('user.user_id'), nullable=False, comment='关联用户 ID')
    category_id = db.Column(db.BigInteger, db.ForeignKey('categories.id'), nullable=False, comment='关联分类 ID')
    type = db.Column(db.Enum(BudgetType), nullable=False, comment='预算类型（月/年度）')
    year = db.Column(db.Integer, nullable=False, comment='年份')
    month = db.Column(db.Integer, nullable=True, comment='月份（年度预算为 NULL）')
    amount = db.Column(db.Numeric(10, 2), nullable=False, comment='分类预算金额')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, comment='更新时间')

    # 关系：关联分类，便于在路由中访问 cb.category.name
    category = db.relationship('Category', backref='category_budgets', lazy=True)

    __table_args__ = (
        db.UniqueConstraint('user_id', 'category_id', 'type', 'year', 'month', name='unique_user_category_type_year_month'),
    )

    def __repr__(self):
        return f'<CategoryBudget {self.id} (user_id: {self.user_id}, category_id: {self.category_id}, type: {self.type.value})>'